package com.example.musicserver.controller;

import com.example.musicserver.common.Constant;
import com.example.musicserver.common.Response;
import com.example.musicserver.mapper.LoveMusicMapper;
import com.example.musicserver.mapper.MusicMapper;
import com.example.musicserver.model.Music;
import com.example.musicserver.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RequestMapping("/music")
@RestController
public class MusicController {
    @Autowired
    private MusicMapper musicMapper;

    @Value("${music.local.path}")
    private String _SAVE_PATH;

    @Autowired
    private LoveMusicMapper loveMusicMapper;

    /**
     * 音乐上传
     * @param singer
     * @param file
     * @param request
     * @param resp
     * @return
     */
    @RequestMapping("/upload")
    public Response<Boolean> insertMusic(@RequestParam String singer,
                                         @RequestParam("filename") MultipartFile file,
                                         HttpServletRequest request,
                                         HttpServletResponse resp) {
        HttpSession session = request.getSession(false);
        // 1. 参数校验
        if (singer == null || singer.length() ==0 || file == null) {
            return new Response<>(-1, "非法参数！", false);
        }

        // 2. 查询数据库中，待上传歌曲是否已经存在
        String fileNameAndType = file.getOriginalFilename();

        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);
        Music music = musicMapper.selectMusicByTitleAndSinger(title, singer);
        if (music != null) {
            return new Response<>(-1, "上传歌曲已存在！", false);
        }

        // 3. 上传到服务器
        String path = _SAVE_PATH +singer+ fileNameAndType;
        File dest = new File(path);
        if (!dest.exists()) {
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new Response<>(-1, "服务器上传失败！", false);
        }

        // 4. 上传到数据库
        User user = (User) session.getAttribute(Constant.USER_SESSION_KEY);
        int uid = user.getId();
        System.out.println(uid);
        String url = "/music/get?path=" + singer +title;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sf.format(new Date());
        try {
            int ret = 0;
            ret = musicMapper.insertMusic(title, singer, time, url, uid);
            if (ret == 1) {
                resp.sendRedirect("/list.html");
                return new Response<>(1, "数据库上传成功！", true);
            } else {
                return new Response<>(-1, "数据库上传失败！", false);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Response<>(-1, "数据库上传失败！", false);
        }
    }

    /**
     * 查询音乐
     * @param
     * @return
     */
    @RequestMapping("/showmusic")
    public Response<List<Music>> showMusic(@RequestParam(required = false) String musicName){
        List<Music> musicList = null;
        if (musicName == null){
           musicList = musicMapper.showMusic();
        }else{
            musicList = musicMapper.showMusicByName(musicName);
        }
        return new Response<>(1,"查询到了所有的音乐",musicList);
    }

    /**
     * 删除单个音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Response<Boolean> deleteMusicById(@RequestParam String id) {
        //1、先检查这个音乐是不是存在的？
        int musicId = Integer.parseInt(id);
        //2、如果存在要进行删除
        Music music = musicMapper.selectMusicById(musicId);
        if(music == null) {
            System.out.println("没有这个id的音乐");
            return new Response<>(-1,"没有你要删除的音乐",false);
        }else {
            //2.1 删除数据库
            int ret = musicMapper.deleteMusicByMusicId(musicId);
            if(ret == 1) {
                //2.2 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index+1);//liu
                File file = new File(_SAVE_PATH+fileName+".mp3");
                System.out.println("当前的路径："+file.getPath());

                if(file.delete()) {
                    //同步删除lovemusic表当中的这个音乐
                    loveMusicMapper.deleteMusicInLikeByMusicId(musicId);
                    return new Response<>(1,"服务器当中的音乐删除成功！",true);
                }else {
                    return new Response<>(-1,"服务器当中的音乐删除失败！",false);
                }
            }else {
                return new Response<>(-1,"数据库当中的音乐没有删除成功！",false);
            }
        }
    }

    /**
     * 批量删除音乐
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/deletemusics")
    public Response<Boolean> deleteMusics(@RequestParam(value = "id[]",required = false) List<String> id,HttpServletRequest request){
        if(id == null || id.size() == 0){
            return new Response<>(-1,"参数异常！",false);
        }

        int sum = 0;
        for (int i = 0; i < id.size(); i++){
            String Id = id.get(i);
            int musicId = Integer.parseInt(Id);
            System.out.println(musicId);
            Music music = musicMapper.selectMusicById(musicId);
            if(music == null){
                return new Response<>(-1,"音乐ID："+musicId+"不存在，无法删除",false);
            }
            int ret = musicMapper.deleteMusicByMusicId(musicId);
            if(ret == 1){
                // 删除服务器上的数据
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index+1);

                File file = new File(_SAVE_PATH+fileName+".mp3");
                if (file.delete()){
                    // 同步删去 lovemusic 中的音乐
                    loveMusicMapper.deleteMusicInLikeByMusicId(musicId);
                    sum += ret;
                }else{
                    return new Response<>(-1,"服务器当中的音乐删除失败！",false);
                }
            }else{
                return new Response<>(-1,"服务器当中的音乐删除失败！",false);
            }
        }

        if(sum == id.size()){
            return new Response<>(1,"音乐删除成功！",true);
        }else{
            return new Response<>(-1,"音乐删除失败！",false);
        }
    }


    /**
     * 播放音乐的时候：/music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(_SAVE_PATH+path);
        byte[] a = null;
        try {
           a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }



}
